package com.chao.auth.controller;

import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

/**
 * @author : Rookie
 * @description :
 * @date : 2022/1/25
 */
@RestController
public class KeyPairController {

    @Autowired
    private KeyPair keyPair;

    @GetMapping("/rsa/publicKey")
    public Map<String,Object> getRSAKey(){
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAKey rsaKey = new RSAKey.Builder(publicKey).build();
        return new JWKSet(rsaKey).toJSONObject();
    }

    @GetMapping("/checkScope")
    @PreAuthorize("#oauth2.hasScope('write')")
    public String check(){
        return "scope校验通过";
    }

    @GetMapping("/currentUser")
    @PreAuthorize("isAuthenticated()")
    public String getCurrentUser(){
        return JSONUtil.toJsonStr(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
    }
}
